package com.usian.security.filter;

import cn.hutool.core.util.StrUtil;
import com.usian.common.utils.JwtUtil;
import com.usian.security.entity.LoginUser;
import com.usian.security.exception.CustomException;
import com.usian.security.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: JwtAuthenticationTokenFilter
 * Author:   WGG
 * Date:    2022-12-2022/12/21-15:53
 * Version: 1.0
 * Description:
 */

/**
 * token认证过滤器
 * 拦截请求，解析token，将token数据保存在SecurityContextHolder
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        //解析token，获取userId
        Long userId;
        try {
            Claims claims = JwtUtil.parseToken(token);
            userId = claims.get("userId", Long.class);
        }catch (Exception e){
            throw  new CustomException("非法token");
        }
        //从redis中获取用户信息
        LoginUser loginUser = redisUtil.get("login:" + userId);
        if (loginUser == null){
            throw new CustomException("用户未登录");
        }
        //存入SecurityContextHolder认证，SecurityContextHolder相当于ThreadLocal
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
